import router from '../../router'

const isMenuHere = function(array, item){
  let isMenu = false
  for (let i = 0; i < array.length; i++) {
    const element = array[i];
    if(element.path === item){
      isMenu = true
      break
    }
  }
  return isMenu
}
const removeSelectMenu = function(array, item){
  for (let i = 0; i < array.length; i++) {
    const element = array[i];
    if(element.path === item.path){
      // 要移除的菜单是当前菜单时
      let curRoutes = router.currentRoute
      if(curRoutes.path == item.path && array.length > 1){
        if(i > 0){
          router.push(array[i-1].path)
        }else if(i == 0 && array.length>0){
          router.push(array[i+1].path)
        }
      }
      if(array.length == 1){
        router.push('/welcome')
      }
      array.splice(i, 1)
    }
  }
  return array
}

const app ={
  state: {
    sidebar: {
      opened: true,
      withoutAnimation: false
    },
    selectMenu: [],
    menuList: [],
  },
  mutations:{
    TOGGLE_SIDEBAR: state =>{
      state.sidebar.opened = !state.sidebar.opened
    },
    SET_SELECT_MENU: (state,data) =>{
      state.selectMenu = data
    },

  },
  actions: {
    ToggleSideBar: ({ commit }) => {
      commit('TOGGLE_SIDEBAR')
    },
    SetSelectMenu:({ commit }, obj) =>{
      let selectMenu =  app.state.selectMenu
      const isMenuSelect = isMenuHere(selectMenu, obj.data.path)
      if(!isMenuSelect){
        selectMenu.push(obj.data)
      }else if(obj.isRemove){
        selectMenu = removeSelectMenu(selectMenu, obj.data)
      }

      commit('SET_SELECT_MENU',selectMenu)
    }
  }
}
export default app